package database;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Properties;

import domain.Speler;
import domain.SpelerTekenChar;
import domain.exceptions.KomtInOrdeException;

public class DatabaseFile implements iDatabase {
	private ArrayList<Speler> spelers = new ArrayList<Speler>();
	Properties fileproperties = null;

	public DatabaseFile() throws IOException, FileNotFoundException,
			KomtInOrdeException {
		this.spelers = new ArrayList<Speler>();
		loadProperties();
		loadDatabase();
	}

	/**
	 * @throws IOException
	 * @throws KomtInOrdeException
	 */
	@Override
	public void loadDatabase() throws IOException, KomtInOrdeException {
		try {
			FileInputStream fstream = new FileInputStream(fileproperties.getProperty("filename"));
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String naam;
			String puntenStr;
			int punten;

			// Read File Line By Line + 2 during the while (waardes onder
			// elkaar)
			// [naam]
			// [punten]
			//
			while ((naam = br.readLine()) != null) {
				puntenStr = br.readLine();
				punten = Integer.parseInt(puntenStr);
				this.addSpeler(naam, punten);
			}

			in.close();
		} catch (FileNotFoundException e) {
			//throw new KomtInOrdeException("Komt in orde");
		}
	}

	@Override
	public ArrayList<Speler> getSpelers() {
		return this.spelers;
	}

	@Override
	public void schrijfGegevensWeg() {
		try {
			FileWriter fstream = new FileWriter(fileproperties.getProperty("filename"));
			BufferedWriter out = new BufferedWriter(fstream);

			for (Speler s : spelers) {
				out.write(s.getSpelerNaam() + "\n");
				out.write(s.getScore() + "\n");
			}
			out.close();

		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}

	}

	@Override
	public Speler getSpeler(String spelerNaam) {
		Speler out = null;
		for (Speler s : spelers) {
			if (s.getSpelerNaam().equals(spelerNaam))
				return s;
		}
		return out;
	}

	@Override
	public boolean addSpeler(String spelerNaam, int score) {
		Speler s= new Speler(spelerNaam, score);
		if (spelers.add(s)){
			return true;
		}
		return false;
	}

	@Override
	public void loadProperties() throws FileNotFoundException, IOException {
		fileproperties = new Properties();
		FileInputStream in = new FileInputStream(this.getClass().getResource("propertiesFile.prp").getPath());
		fileproperties.load(in);
		in.close();
	}

	@Override
	public void updateSpelerScore(Speler speler) {
		int i = 0;
		for (Speler s : spelers) {
			if (s.getSpelerNaam().equals(speler.getSpelerNaam())){
				break;
			}
			i++;
		}
		spelers.remove(i);
		spelers.add(speler);
		schrijfGegevensWeg();
	}

}
